import { nextTick, onUnmounted, ref, watch } from "vue";
import { useElementSize } from "@vueuse/core";
import { BarChart, GaugeChart, LineChart, PictorialBarChart, PieChart, RadarChart, ScatterChart } from "echarts/charts";
import { DatasetComponent, GridComponent, LegendComponent, TitleComponent, ToolboxComponent, TooltipComponent, TransformComponent, } from "echarts/components";
import * as echarts from "echarts/core";
import { LabelLayout, UniversalTransition } from "echarts/features";
import { CanvasRenderer } from "echarts/renderers";
echarts.use([
    TitleComponent,
    LegendComponent,
    TooltipComponent,
    GridComponent,
    DatasetComponent,
    TransformComponent,
    ToolboxComponent,
    BarChart,
    LineChart,
    PieChart,
    ScatterChart,
    PictorialBarChart,
    RadarChart,
    GaugeChart,
    LabelLayout,
    UniversalTransition,
    CanvasRenderer,
]);
/**
 * Echarts hooks函数
 * @param options - 图表配置
 * @param renderFun - 图表渲染函数(例如：图表监听函数)
 * @description 按需引入图表组件，没注册的组件需要先引入
 */
export const useEcharts = (options, renderFun) => {
    const domRef = ref();
    const initialSize = { width: 0, height: 0 };
    const { width, height } = useElementSize(domRef, initialSize);
    let chart = null;
    const canRender = () => {
        return initialSize.width > 0 && initialSize.height > 0;
    };
    const isRendered = () => {
        return Boolean(domRef.value && chart);
    };
    const update = (updateOptions) => {
        if (isRendered()) {
            chart.setOption({ ...updateOptions, backgroundColor: "transparent" });
        }
    };
    const render = async () => {
        if (domRef.value) {
            await nextTick();
            chart = echarts.init(domRef.value);
            update(options.value);
            if (renderFun) {
                renderFun(chart);
            }
        }
    };
    const resize = () => {
        chart?.resize();
    };
    const destroy = () => {
        chart?.dispose();
    };
    const stopSizeWatch = watch([width, height], ([newWidth, newHeight]) => {
        initialSize.width = newWidth;
        initialSize.height = newHeight;
        if (newWidth === 0 && newHeight === 0) {
            // 节点被删除 将chart置为空
            chart = null;
        }
        if (canRender()) {
            if (!isRendered()) {
                render();
            }
            else {
                resize();
            }
        }
    });
    const stopOptionWatch = watch(options, (newValue) => {
        update(newValue);
    });
    onUnmounted(() => {
        destroy();
        stopSizeWatch();
        stopOptionWatch();
    });
    return {
        domRef,
    };
};
